package org.van.financial.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.van.financial.constant.LogActions;
import org.van.financial.constant.WebConst;
import org.van.financial.exception.BusinessException;
import org.van.financial.model.UserDomain;
import org.van.financial.service.log.LogService;
import org.van.financial.service.user.UserService;
import org.van.financial.utils.APIResponse;
import org.van.financial.utils.TaleUtils;

@Controller
@RequestMapping("/api")
public class AuthController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @PostMapping(value = "/login")
    @ResponseBody
    public APIResponse<?> toLogin(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(name = "username", required = true) String username,
            @RequestParam(name = "password", required = true) String password,
            @RequestParam(name = "remember_me", required = false) String remember_me) {
        Integer error_count = cache.get("login_error_count");
        try {
            UserDomain userInfo = userService.login(username, password);
            request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, userInfo);
            if (StringUtils.isNotBlank(remember_me)) {
                TaleUtils.setCookie(response, userInfo.getUid());
            }
            logService.addLog(LogActions.LOGIN.getAction(), userInfo.getUsername() + "User", request.getRemoteAddr(),
                    userInfo.getUid());
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            error_count = null == error_count ? 1 : error_count + 1;
            if (error_count > 3) {
                return APIResponse.fail("Try it again 10min later!");
            }
            System.out.println(error_count);
            cache.set("login_error_count", error_count, 10 * 60);
            String msg = "Login Failed!";
            if (e instanceof BusinessException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return APIResponse.fail(msg);
        }
        return APIResponse.success();
    }

    @RequestMapping(value = "/logout")
    public void logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
        Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
        cookie.setValue(null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    @RequestMapping(value = "/register")
    @ResponseBody
    public APIResponse<?> register(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(name = "username", required = true) String username,
            @RequestParam(name = "password", required = true) String password,
            @RequestParam(name = "remember_me", required = false) String remember_me) {

        UserDomain user = new UserDomain();
        user.setUsername(username);
        user.setPassword(password);
        try {
            userService.register(user);

        } catch (Exception e){
            return APIResponse.fail("");
        }
        return APIResponse.success();
    }

}
